// axios的二次封装
import axios from "axios";
import { message } from "antd";
import { getToken, getRefreshToken, clearTokens } from "./token"; // 假设有获取refreshToken的方法

// 创建基础实例
export const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASEURL || "/api",
  timeout: 10000,
});

// 创建无拦截器的专用刷新实例
const refreshRequest = axios.create({
  baseURL: import.meta.env.VITE_API_BASEURL || "/api",
  timeout: 10000,
});

// 刷新状态管理
let isRefreshing = false;
let requests: ((token: string) => void)[] = [];
let num = 0;
// 请求拦截器
request.interceptors.request.use((config) => {
  const token = getToken();
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }

  // Loading控制（保持原有逻辑）
  num++;
  if (num > 0) {
    document.getElementById("loading")!.style.display = "block";
  }

  return config;
});

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    // 成功处理
    num--;
    handleLoading();
    return response.data;
  },
  async (error) => {
    // 错误处理
    num--;
    handleLoading();

    const { config, response } = error;
    if (!response) return Promise.reject(error);

    // Token过期处理
    if (response.status === 401 && !config._retry) {
      if (response.data.code === 401) {
        return handleTokenExpired(config);
      }
    }

    // 其他错误处理
    handleErrorCode(response.status);
    return Promise.reject(error);
  }
);

// 处理Token过期
async function handleTokenExpired(config: any) {
  if (!isRefreshing) {
    isRefreshing = true;
    config._retry = true;

    try {
      const res = await refreshToken();
      const newToken = res.data.accessToken;
      setNewToken(newToken);

      // 重试队列中的请求
      requests.forEach((cb) => cb(newToken));
      requests = [];
      return request(config);
    } catch (refreshError) {
      // 刷新失败处理
      clearTokens();
      window.location.href = "/login";
      return Promise.reject(refreshError);
    } finally {
      isRefreshing = false;
    }
  }

  // 正在刷新时，返回等待的Promise
  return new Promise((resolve) => {
    requests.push((token: string) => {
      config.headers.Authorization = `Bearer ${token}`;
      resolve(request(config));
    });
  });
}

// 专用刷新Token方法
async function refreshToken() {
  try {
    return await refreshRequest.get("/refresh", {
      params: {
        refreshToken: getRefreshToken(),
      },
      // 跳过拦截器
      skipAuthRefresh: true,
    });
  } catch (error) {
    clearTokens();
    throw error;
  }
}

// 工具函数
function setNewToken(token: string) {
  localStorage.setItem("token", token);
  request.defaults.headers.common["Authorization"] = `Bearer ${token}`;
}

function handleLoading() {
  if (num < 1) {
    setTimeout(() => {
      document.getElementById("loading")!.style.display = "none";
    }, 1000);
  }
}

function handleErrorCode(code: number) {
  const errorMessages = {
    400: "请求语法错误",
    401: "需要身份验证",
    403: "服务器拒绝请求",
    404: "页面资源未找到",
    500: "服务器错误",
  };
  message.error(errorMessages[code] || `未知错误: ${code}`);
}
